from flask import Blueprint, request, jsonify
from app.services.travel_service import TravelService

travel_bp = Blueprint('travel', __name__)
travel_service = TravelService()

@travel_bp.route('/api/travel/plan', methods=['GET'])
def plan_route():
    """路线规划接口"""
    try:

        # 获取前端请求传递的params
        start_address = request.args.get('start_address')
        end_address = request.args.get('end_address')
        travel_mode = request.args.get('travel_mode', 'driving')

        # 如果是驾驶模式
        if travel_mode == "driving":
            travel_preference = request.args.get('travel_preference', '0')

            # 将起点和终点地址转换为经纬度
            start_location = travel_service.geocode(start_address)
            end_location = travel_service.geocode(end_address)

            # 将经纬度对象转换为字符串格式
            start_point = f"{start_location['lat']},{start_location['lng']}"
            end_point = f"{end_location['lat']},{end_location['lng']}"

            if not start_point or not end_point:
                return jsonify({
                    'success': False,
                    'message': '起点和终点不能为空'
                }), 400

            # 调用接口
            result = travel_service.get_travel_plan(
                start_point=start_point,
                end_point=end_point,
                travel_mode=travel_mode,
                route_preference=travel_preference
            )

            return jsonify({
                'success': True,
                'data': result
            })
        
        else:
            # 将起点和终点地址转换为经纬度
            start_location = travel_service.geocode(start_address)
            end_location = travel_service.geocode(end_address)

            # 将经纬度对象转换为字符串格式
            start_point = f"{start_location['lat']},{start_location['lng']}"
            end_point = f"{end_location['lat']},{end_location['lng']}"

            if not start_point or not end_point:
                return jsonify({
                    'success': False,
                    'message': '起点和终点不能为空'
                }), 400
            
            result = travel_service.get_travel_plan(
                start_point=start_point,
                end_point=end_point,
                travel_mode=travel_mode,
            )

            return jsonify({
                'success': True,
                'data': result
            })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500 